/**
 * 
 */
package com.mbengue.corp.apr.ra.util;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

/**
 * @author MMB11447
 *
 */
public class HibernateUtil {
  private static final SessionFactory SESSION_FACTORY;
  private static Session SESSION;
  static {
    try {
      Configuration configuration = new Configuration();
      configuration.configure();
      ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties())
          .buildServiceRegistry();
      SESSION_FACTORY = configuration.buildSessionFactory(serviceRegistry);
      SESSION = SESSION_FACTORY.openSession();
    } catch (HibernateException ex) {
      // Log exception!
      throw new ExceptionInInitializerError(ex);
    }
  }

  public static Session getSessionFactory() throws HibernateException {
    if (!SESSION.isOpen()) {
      SESSION = SESSION_FACTORY.openSession();
      return SESSION;
    }
    return SESSION;
  }
}
